<?php

namespace App\Http\Controllers;

use App\Article;
use App\Episode;
use App\Image;
use App\Movie;
use App\Show;
use App\Tag;
use App\User;
use App\Vote;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Session;

class ArticleController extends Controller
{

    public function __construct()
    {
        $this->middleware(['auth', 'admin'], ['except' => ['fetchImageBy', 'show', 'hotArticles', 'publicToToutiao']]);

        $accessKey = env('QN_accessKey');
        $secretKey = env('QN_secretKey');
        $this->qnAuth = new Auth($accessKey, $secretKey);
        $this->bucketMgr = new BucketManager($this->qnAuth);
    }


    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $articles = Article::orderBy('created_at', 'desc')->paginate(200);
        return view('articles.index', compact('articles'));
    }

    public function hotArticles()
    {
        $articles = Article::withTrashed()->orderBy('created_at', 'desc')->paginate(20);
        $title = '最新-美剧资源-美剧段子-视频-搞笑图片';
        return view('articles.hotArticles', compact('articles', 'title'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $tags_array = [];
        foreach (Tag::all() as $vo) {
            $tags_array[$vo->id] = $vo->name . $vo->name_en;
        }
        $tags = collect($tags_array);
        $shows_array = [];
        foreach (Show::all() as $vo) {
            $shows_array[$vo->id] = $vo->name_zh . $vo->name_en;
        }
        $shows = collect($shows_array);
        $movies_array = [];
        foreach (Movie::all() as $vo) {
            $movies_array[$vo->id] = $vo->name_zh . $vo->name_en;
        }
        $movies = collect($movies_array);
        $article = new Article();
        return view('articles.create', compact('tags', 'shows', 'movies', 'article'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'title' => 'required|max:254',
        ]);
        $title = $request->input('title');
        $article = Article::firstOrCreate(['raw_title' => $title]);
        $article->title = $title;
        $article->raw_content = $request->input('body');
        $article->body = $request->input('body');
        $article->keyword = $request->input('key_word');
        $article->description = $request->input('description');
        $article->url_video = $request->input('url_video');
        $article->save();
        //绑定文章到 剧集
        $array_show = $request->input('show_list');
        $array_tags = $request->input('tag_list');
        $array_movies = $request->input('movie_list');

        if (count($array_movies) > 0) {
            $article->movies()->sync($array_movies);
        }
        if (count($array_show) > 0) {
            $article->shows()->sync($array_show);
        }
        if (count($array_tags) > 0) {
            $article->tags()->sync($array_tags);
        }
        Session::flash('success', '博客发表成功!');
        return redirect("/article/{$article->id}/edit");
    }

    public function fetchImageBy($url, $key)
    {
        $bucket = env('QN_bucketName');
        list($ret, $err) = $this->bucketMgr->fetch($url, $bucket, $key);
        if ($err !== null) {
            Session::flash('error', $url);
        } else {
//            $image = Image::firstOrNew(['key'=>$key]);
//            $image->mimeType = $ret['mimeType'];
//            $image->fsize = $ret['fsize'];
//            $image->fname= $url;
//            $image->description=$url;
//            $image->bucket = $bucket;
//            return $image;
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show(Article $article)
    {
//        $imgs = [];
//        foreach ($article->images as $img) {
//            $fname = $img->fname;
//            $src = $img->getUrl();
//            $imgs[] = compact('src', 'fname');
//        }
//        $imgs = json_encode($imgs, JSON_UNESCAPED_SLASHES);
        return redirect('//www.mojotv.cn/article/' . $article->id, 301);
//        return view('articles.show', compact('article', 'imgs'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Article $article, Request $request)
    {


        $tags_array = [];
        foreach (Tag::all() as $vo) {
            $tags_array[$vo->id] = $vo->name . $vo->name_en;
        }
        $tags = collect($tags_array);
        $shows_array = [];
        foreach (Show::all() as $vo) {
            $shows_array[$vo->id] = $vo->name_zh . $vo->name_en;
        }
        $shows = collect($shows_array);
        $movies_array = [];
        foreach (Movie::all() as $vo) {
            $movies_array[$vo->id] = $vo->name_zh . $vo->name_en;
        }
        $movies = collect($movies_array);


        return view('articles.edit', compact('article', 'tags', 'shows', 'movies'));
    }

    public function editWang(Article $article, Request $request)
    {
        $tags = Tag::pluck('name', 'id');
        $shows = Show::pluck('name_en', 'id');
        $movies = Movie::pluck('name_en', 'id');
        return view('articles.editWang', compact('article', 'tags', 'shows', 'movies'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Article $article)
    {
        Vote::firstOrCreate(['article_id' => $article->id]);
        $para = $request->all();
        $para = array_only($para, ['body', 'title', 'url_video', 'key_word', 'is_show', 'description', 'video_title']);
        $article->update($para);
        $article->save();

        $tagsIds = $request->input('tag_list');
        $showIds = $request->input('show_list');
        $movieIds = $request->input('movie_list');
        if (count($tagsIds) > 0) {
            $article->tags()->sync($tagsIds);
        }
        if (count($showIds) > 0) {
            $article->shows()->sync($showIds);
            //自动创建封面
            if (empty($article->coverage_uri) and !empty($article->shows)) {
                try {
                    $article->coverage_uri = $article->shows->last()->images->last()->key;
                    $article->save();
                } catch (\Exception $e) {
                    \Log::alert('自动设置封面失败' . $e->getMessage());
                }
            }
        }
        if (count($movieIds) > 0) {
            $article->movies()->sync($movieIds);
        }


        //通过key word 关联 episode资源
        $keyWords = preg_split('/\s+/', $article->key_word);
        $regexString = '';
        foreach ($keyWords as $word) {
            $regexString .= "($word)|";
        }
        $regexString = trim($regexString, '|');
        $epIDs = Episode::where('raw_name', 'REGEXP', $regexString)
            ->orderBy('updated_at', 'desc')
            ->get()->pluck('id')
            ->toArray();
        $article->episodes()->sync($epIDs);
        Session::flash('success', '修改成功!');


        return redirect(route('article.edit', $article));

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Article $article)
    {
        $article->delete();
        return response()->json(['status' => 'success']);
    }


    public function showRelatedArticles(Show $show)
    {

        return view('articles.index', ['articles' => $show->articles]);
    }


    public function publishTriggerAction(Request $request)
    {
        $id = $request->input('articleId');
        $article = Article::find($id);
        if ($article) {
            $article->is_show = !$article->is_show;
            $message = $article->is_show ? '隐藏' : '发表';
            $article->save();
            return ['message' => $message, 'code' => '1'];
        } else {
            return ['message' => '没有这个文章', 'code' => '0'];
        }

    }

    public function setCoverage(Request $request)
    {
        $articleId = $request->input('articleId');
        $imageId = $request->input('imageId');
        $image = Image::find($imageId);
        $res = Article::where(['id' => $articleId])->update(['coverage_uri' => $image->key]);
        return response()->json($res);
    }


    public function publicToWeibo(Article $article)
    {
        $token = User::whereWeiboId('2706451481')->first()->weibo_token;
        //$token = '2.00PfzJxC5FNO8D0dbb450c3bTtl59E';
        //http://open.weibo.com/wiki/2/proxy/article/publish

        //处理图片
        //提换图片
        $waterMarker = '?imageView2/0/q/75|watermark/2/text/bW9qb1RW/font/6buR5L2T/fontsize/420/fill/I0ZGRkZGRg==/dissolve/100/gravity/NorthWest/dx/10/dy/10|imageslim';
        $content = $article->body;
        foreach ($article->images as $img) {
            $src = 'http://img.trytv.org/' . $img->key . $waterMarker;
            $content = str_ireplace($img->fname, $src, $content);
        }


        $client = new Client();
        $mojo_url = 'http://www.mojotv.cn/article/' . $article->id;
        $body_h1 = "<h1><a target='_blank' href='http://video.trytv.org/search/game%20of%20throne'>权利的游戏在线看</a></h1><h2><a target='_blank' href='{$mojo_url}'>{$article->title}</a></h2>";
        $content = $body_h1 . $article->body;


        $hashTag = '#美剧#';
        if (!empty($article->shows)) {
            $show = $article->shows->first();
            if (!empty($show->name_zh)) {
                $hashTag = $hashTag . "#{$show->name_zh}#";
            }
            if (!empty($show->name_zh)) {
                $hashTag = $hashTag . "#{$show->name_en}#";
            }
        }
        $response = $client->request('POST', 'https://api.weibo.com/proxy/article/publish.json', [
            'form_params' => [
                'title' => mb_substr($article->title, 0, 32),//文章标题，限定32个中英文字符以内
                'content' => $content,//正文内容，限制90000个中英文字符内，需要urlencode
                'cover' => "http://img.trytv.org/{$article->coverage_uri}",//文章封面图片地址url
                'summary' => mb_substr($article->description, 0, 199),//文章导语
                'text' => $hashTag . $article->description . $mojo_url,//与其绑定短微博内容，限制1900个中英文字符内
                'access_token' => $token,//认证token
            ]
        ]);

        echo $response->getBody();
        $json = \GuzzleHttp\json_decode($response->getBody());

        if ($json->code == 100000) {
            return redirect($json->data->url);
        }
        dd($json);
    }

    public function publicToToutiao(Article $article)
    {
        $token = session('toutiao_token');
        //dd($token);
        $token = '8345f7edda47cde15f4b200131bcf24d0011';
        if (empty($token)) {
            return redirect('/auth/toutiao');
        }
        //dd($token);
        //$token = '2.00PfzJxC5FNO8D0dbb450c3bTtl59E';
        //http://open.weibo.com/wiki/2/proxy/article/publish

        //处理图片
        //提换图片
        $waterMarker = '?imageView2/0/q/75|watermark/2/text/bW9qb1RW/font/6buR5L2T/fontsize/420/fill/I0ZGRkZGRg==/dissolve/100/gravity/NorthWest/dx/10/dy/10|imageslim';
        $content = $article->body;
        foreach ($article->images as $img) {
            $src = 'http://img.trytv.org/' . $img->key . $waterMarker;
            $content = str_ireplace($img->fname, $src, $content);
        }


        $client = new Client();
        $mojo_url = 'http://www.mojotv.cn/article/' . $article->id;
        $body_h1 = "";
        $content = $body_h1 . $article->body;
        $response = $client->request('POST', 'https://mp.toutiao.com/open/new_article_post/', [
            'form_params' => [
                'access_token' => $token,
                'client_key' => 'b6c1c1b63946497b',
                'title' => mb_substr($article->title, 0, 32),//文章标题，限定32个中英文字符以内
                'content' => $content,//正文内容，限制90000个中英文字符内，需要urlencode
                'abstract' => $article->description,//文章导语
                'save' => '0',
                'article_tag' => 'news_entertainment',
            ]
        ]);

        echo $response->getBody();
        $json = \GuzzleHttp\json_decode($response->getBody());

        dd($json);
    }


}
